// api/session_api/session_list.go
package session_api

import (
	"github.com/gin-gonic/gin"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/models/ctype"
	"muziai-server/service/common"
	"muziai-server/utils/jwts"
	"muziai-server/utils/res"
	"time"
)

type SessionListRequest struct {
	models.Page
	Type   int8 `json:"type" form:"type" binding:"required,oneof=1 2"` //1 用户个人会话 2全部会话管理员用
	RoleID uint `json:"roleID" form:"roleID"`
	UserID uint `json:"userID" form:"userID"`
}
type SessionListResponse struct {
	models.SessionModel
	AiRoleAvatar    string    `json:"aiRoleAvatar"`
	AiRoleTitle     string    `json:"aiRoleTitle"`
	ChatLastContent string    `json:"chatLastContent"`
	ChatCount       int       `json:"chatCount"`
	ChatLastDate    time.Time `json:"chatLastDate"`
	UserNickname    string    `json:"userNickname"`
	UserAvatar      string    `json:"userAvatar"`
}

func (SessionApi) SessionListView(c *gin.Context) {
	var cr SessionListRequest
	err := c.ShouldBindQuery(&cr)
	if err != nil {
		res.FailWithError(c, err)
		return
	}

	_claims, _ := c.Get("claims")
	claims := _claims.(*jwts.Claims)
	if claims.Role == ctype.AuthRole && cr.Type == 2 {
		res.FailWithMsg(c, "权限错误")
		return
	}
	var query = global.DB.Where("")
	var preloads = []string{"UserModel", "RoleModel", "ChatList"}
	if cr.Type == 1 {
		preloads = []string{"RoleModel", "ChatList"}
		query.Where("user_id = ?", claims.UserID)
	}
	//if cr.Order == "" {
	//	cr.Order = "created_at desc"
	//}
	_list, count, _ := common.QueryList(models.SessionModel{
		RoleID: cr.RoleID,
		UserID: cr.UserID,
	}, common.Option{
		Page:     cr.Page,
		Likes:    []string{"title"},
		Preloads: preloads,
		Where:    query,
		Sort:     "created_at desc",
	})
	var list = make([]SessionListResponse, 0)
	for _, model := range _list {

		var lastChat models.ChatModel
		if len(model.ChatList) > 0 {
			lastChat = model.ChatList[len(model.ChatList)-1]
		}

		list = append(list, SessionListResponse{
			SessionModel:    model,
			AiRoleAvatar:    model.RoleModel.Avatar,
			AiRoleTitle:     model.RoleModel.Title,
			ChatLastContent: lastChat.UserContent,
			ChatCount:       len(model.ChatList),
			ChatLastDate:    lastChat.CreatedAt,
			UserNickname:    model.UserModel.Nickname,
			UserAvatar:      model.UserModel.Avatar,
		})
	}
	res.OkWithList(c, list, count)
}
